<template>
  <div class="search-container">
    <form action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isClickEnter = false"
      />
    </form>

    <search-result
      v-if="isClickEnter"
      :searchText="searchText"
    />

    <search-suggestion
      :searchText="searchText"
      v-else-if="searchText"
      @search="onSearch"
    />

    <search-history
      v-else
      :historyList="historyList"
      @search="onSearch"
      @delete-all="historyList = []"
    />
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchResult from './components/search-result.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import { setItem, getItem } from '@/utils/storage'

export default {
  name: 'search-page',
  components: {
    SearchHistory,
    SearchResult,
    SearchSuggestion,
  },
  data () {
    return {
      searchText: '',
      isClickEnter: false,
      historyList: getItem('HISTORY-LIST') || []
    }
  },
  methods: {
    onSearch (val) {
      this.searchText = val
      this.isClickEnter = true

      if (this.historyList.includes(val)) {  // 判断数组里 是否已经存过了  如果为 true代表 存储过了
        // 把之前存的数据删除

        let index = this.historyList.indexOf(val)   // 找到存在的元素的索引

        this.historyList.splice(index, 1)  // 进行删除操作
      }

      this.historyList.unshift(val)  // 把刚才搜索的内容 放到数组里

      this.$toast(val)
    },
    onCancel () {
      this.$toast('取消搜索')
    }
  },
  watch: {
    historyList(val) {
      setItem('HISTORY-LIST', val)
    }
  }
}
</script>

<style lang="less" scoped>
.search-container {
  padding-top: 108px;

  .van-search--show-action {
    background-color: #3296fa;
    .van-search__action {
      color: #fff;

      &:active {
        background-color: #3296fa;
      }
    }

  }
  .van-search {
    position: fixed;
    z-index: 999;
    left: 0;
    right: 0;
    top: 0;
    height: 108px;
  }

}
</style>
